package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    RestHighLevelClient client;
    @Autowired
    IHotelService hotelService;

    @Override
    public PageResult search(RequestParams params) {
        //1.创建搜索请求
        try {
            SearchRequest request = new SearchRequest("hotel");
            //2.设置条件  request.sourse().query();
            buildBasicQuery(params, request);
            //4执行搜索请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //5 处理解析结果
            return handleResponse(response);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("搜索出现异常 异常的原因{}：", e.getMessage());
        }

        return null;
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        //1.创建搜索条件
        SearchRequest request = new SearchRequest();
        //搜索条件的设置 复用search方法条件
        buildBasicQuery(params,request);
        //设置聚合处理 要求 按照 品牌 星级 城市 进行terms分桶
        request.source().size(0);
        request.source().aggregation(
                AggregationBuilders.terms("brandAgg")
                .field("brand")
                .size(20)
        ); request.source().aggregation(
                AggregationBuilders.terms("starAgg")
                .field("starName")
                .size(20)
        ); request.source().aggregation(
                AggregationBuilders.terms("cityAgg")
                .field("city")
                .size(20)
        );
        //2.执行搜索
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //获取聚合结果
            //3.解析响应聚合结果
            Aggregations aggregations = response.getAggregations();
            List<String> brandAgg = getAggByName(aggregations, "brandAgg");
            List<String> starAgg = getAggByName(aggregations, "starAgg");
            List<String> cityAgg = getAggByName(aggregations, "cityAgg");

            //要求 按照 品牌 星际 城市解析聚合结果 封装到map集合中
            Map<String,List<String>> result = new HashMap<>();
            result.put("brand",brandAgg);
            result.put("starName",starAgg);
            result.put("city",cityAgg);
            return result;

        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("聚合条件搜索失败");

        }


    }

    @Override
    public List<String> suggestion(String key) {
        //1.准备参数
        SearchRequest request =  new SearchRequest("hotel");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "mySuggestion",
                SuggestBuilders.completionSuggestion("suggestion")
                .prefix(key)
                .skipDuplicates(true)
                .size(10)

        ));

        //2.请求请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            //按照自定义名称
     CompletionSuggestion suggestion =suggest.getSuggestion("mySuggestion");
     //所有的options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
               list.add(option.getText().toString()) ;
            }
            //3.解析响应
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("自动补全查询出现异常");
        }

    }

    @Override
    public void insert(Long hotelId) {
        try {
        Hotel hotel = hotelService.getById(hotelId);
        HotelDoc hotelDoc = new HotelDoc(hotel);
        //1.创建
        IndexRequest request = new IndexRequest("hotel");
        request.id(String.valueOf(hotelDoc.getId()));
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
        //2.执行

            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(" 删除文档失败 文档id ：{}   失败原因：{}",hotelId,e.getMessage());
        }

    }

    @Override
    public void delete(Long hotelId) {
        try {
        //1.创建
        DeleteRequest request = new DeleteRequest("hotel",String.valueOf(hotelId));
        //2.执行

            client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(" 删除文档失败 文档id ：{}   失败原因：{}",hotelId,e.getMessage());
        }

    }

    public List<String> getAggByName(Aggregations aggregations,String name) {
        Terms brandAgg = aggregations.get("brandAgg");//品牌的聚合结果
        List<String> list = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            list.add(bucket.getKeyAsString());

        }
        return list;
    }


    public void buildBasicQuery(RequestParams params, SearchRequest request) {
        //1.准备bool query条件查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            //key不为空
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        if (StringUtils.isNotBlank(params.getCity())) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        if (StringUtils.isNotBlank(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if (StringUtils.isNotBlank(params.getStarName())) {
            boolQuery.filter(QueryBuilders.termQuery("startName", params.getStarName()));
        }
        if (params.getMaxPrice() != null && params.getMinPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice())
                    .gte(params.getMinPrice()));
        }
        //3分页
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1) * size).size(size);
        //4.判断是否包含 location 如果包含 设置 按照距离排序
        if (StringUtils.isNotBlank(params.getLocation())) {
            request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(params.getLocation()))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS)
            );

        }
        //5. 当 isAD字段 如果为true 需要重新计算文档得分 ：原有得分*5
        // 构建算分函数
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
        boolQuery,// 原来的bool查询条件
        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{  //可以有多个算分函数
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD",true),
                        ScoreFunctionBuilders.weightFactorFunction(5)),


        }
        );
        request.source().query(functionScoreQueryBuilder);
    }

        public PageResult handleResponse (SearchResponse response){
            SearchHits hits = response.getHits();
            long total = hits.getTotalHits().value; // 总数量
            SearchHit[] docArr = hits.getHits();
            List<HotelDoc> list = new ArrayList<>();
            for (SearchHit dos : docArr) {
                HotelDoc hotelDoc = JSON.parseObject(dos.getSourceAsString(), HotelDoc.class);
                //查询排序距离的值
                Object[] sortValues = dos.getSortValues();
                if (sortValues.length>0){
                    hotelDoc.setDistance(sortValues[0]);
                }
                list.add(hotelDoc);
            }
            return new PageResult(total, list);
        }
    }
